package com.wisenet.wx.util;

import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.List;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.log4j.Logger;

public class FileUtil {
	
	private static Logger logger = Logger.getLogger(FileUtil.class);

	/**
     * 发送https请求获取临时素材 
     * @param requestUrl
     * @return
     * @throws Exception
     */
	public static HttpsURLConnection getFile(String requestUrl) throws Exception {
		// 创建SSLContext对象，并使用我们指定的信任管理器初始化
		TrustManager[] tm = { new MyX509TrustManager() };
		SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
		sslContext.init(null, tm, new java.security.SecureRandom());
		// 从上述SSLContext对象中得到SSLSocketFactory对象
		SSLSocketFactory ssf = sslContext.getSocketFactory();

		URL url = new URL(requestUrl);
		HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();
		httpUrlConn.setSSLSocketFactory(ssf);

		httpUrlConn.setDoOutput(true);
		httpUrlConn.setDoInput(true);
		httpUrlConn.setUseCaches(false);
		// 设置请求方式
		httpUrlConn.setRequestMethod("GET");

		httpUrlConn.connect();
		return httpUrlConn;
	}
	
	/**
	 * 保存图片
	 * @param inputStream
	 * @param savePath
	 */
	public static void savePicture(InputStream inputStream, String savePath) {
		DataInputStream dataInputStream = null;
		FileOutputStream fileOutputStream = null;
		try {
			dataInputStream = new DataInputStream(inputStream);
			//建立一个新的文件
	        fileOutputStream = new FileOutputStream(new File(savePath));
	        int length;
	        byte[] buffer = new byte[1024];
	        //开始填充数据 
	        while((length = dataInputStream.read(buffer)) > 0) {
	        	fileOutputStream.write(buffer, 0, length);  
	        }
		} catch (Exception ex) {
			logger.info("error: " + ex.getMessage());
		} finally {
			try {
				if(fileOutputStream != null) fileOutputStream.close();
				if(dataInputStream != null) dataInputStream.close();
				if(inputStream != null) inputStream.close();
				inputStream = null;
				dataInputStream = null;
				fileOutputStream = null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	/**
	 * 获取图片扩展名
	 * @param contentType
	 * @return
	 */
	public static String getExt(String contentType) {
		if ("image/jpeg".equals(contentType)) {
			return ".jpg";
		}
		if ("image/png".equals(contentType)) {
			return ".png";
		}
		if ("image/gif".equals(contentType)) {
			return ".gif";
		}
		return ".jpg";
	}
	
	/**
	 * 获取上传文件
	 * @param request
	 * @return
	 * @throws IOException
	 */
	public static FileItem getFile(HttpServletRequest request) throws IOException {
		try {
			request.setCharacterEncoding("UTF-8");
			// 创建一个DiskFileItemFactory工厂
			DiskFileItemFactory factory = new DiskFileItemFactory();
			// 创建一个文件上传解析器
			ServletFileUpload upload = new ServletFileUpload(factory);
			// 解决上传文件名的中文乱码
			upload.setHeaderEncoding("UTF-8");
			// 得到 FileItem 的集合 items
			@SuppressWarnings("unchecked")
			List<FileItem> items = upload.parseRequest(request);
			// 遍历 items
			for (FileItem item : items) {
				String name = item.getFieldName();
				if (!item.isFormField() && "myimage".equals(name)) {
					return item;
				}
			}
		} catch (Exception e) {
			logger.info("错误：" + e.getMessage());
		}
		return null;
	}
	
	/**
	 * 获取图片字节
	 * @param item
	 * @return
	 */
	public static byte[] getFileByte(FileItem item) {
		InputStream input = null;
		ByteArrayOutputStream outputStream = null;
		try {
			outputStream = new ByteArrayOutputStream();
			input = item.getInputStream();
			byte[] buff = new byte[1024];
			int rc = 0;
			while ((rc = input.read(buff)) > 0) {
				outputStream.write(buff, 0, rc);
			}
			return outputStream.toByteArray();
		} catch (Exception e) {
			logger.info("图片异常: " + e.getMessage());
		} finally {
			try {
				if (outputStream != null) outputStream.close();
				if (input != null) input.close();
			} catch (IOException e) {
				logger.info("关闭流异常: " + e.getMessage());
			}
		}
		return null;
	}
}
